const router = require("koa-router")();
const CheckModel = require("../models/check.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");
const formatDateHelper = require('../utils/formatDateHelper.js')


router.get("/checks", async ctx => {
	let {
		page,
		limit,
		check_date
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};
	
	
	// 构建查询条件
	if (check_date) {
		query.check_date = {
			$regex: ctx.query.check_date
		}; // 不区分大小写的正则表达式
	}
	

	var data = await CheckModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await CheckModel.find(query).countDocuments();
	ctx.body = {
		code: 200,
		data: data,
		total,
		msg: "ok"
	}

})

router.post("/check", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		check_date,
		name,
		remark,
		create,
		modify
	} = ctx.request.body;
	
	if (!check_date) {
		return ResultHelper.errInfo422(ctx, "请选择排查日期")
	}
	if (!name) {
		return ResultHelper.errInfo422(ctx, "请填写巡检人")
	}
	

	if (!id) {
		
		const carPost = new CheckModel({
			id,
			check_date,
			name,
			remark,
			create,
			modify
		});
		const res = await carPost.save();
		ctx.body = {
			code: 200,
			msg: "添加成功"
		}
	} else {
		// 已存在数据
		// 获取下数据的内容
		const item = await CheckModel.findOne({
			id: ctx.request.body.id
		});
		const res = await CheckModel.updateOne({
			id: id
		}, {
			$set: {
				id,
				check_date: ctx.request.body.check_date ? ctx.request.body.check_date : item.check_date,
				name: ctx.request.body.name ? ctx.request.body.name : item.name,
				remark: ctx.request.body.remark ? ctx.request.body.remark : item.remark,
				create: ctx.request.body.create ? ctx.request.body.create : item.create,
				modify: formatDateHelper.date()
			}
		});
		ctx.body = {
			code: 200,
			msg: "编辑成功"
		}
	}
})


module.exports = router;
